const { assert } = require('console')
const EventEmiter = require('events')
class Usecase extends EventEmiter {
  constructor(events = [], logger = { info: console.log }) {
    super()
    this.logger = logger
    this.eventMap = events.reduce(
      (acc, item) => ({ ...acc, [item]: item }),
      Object.create(null)
    )
    return this
  }
  assertEvent(event) {
    assert(
      event in this.eventMap,
      `监听事件失败，用例【${this.constructor.name}】 没有这个事件: ${event}`
    )
  }
  on(event, handle) {
    this.assertEvent(event)
    this.log(event)
    this.addListener(event, handle)
    return this
  }

  log(event) {
    const name = this.constructor.name
    const message = `[Usecase ${name}] 业务事件：${event} 已监听`
    this.logger.info(message)
  }
}

module.exports = Usecase
